function timestampToTime(timestamp) {
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    Y = date.getFullYear() + '-';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';
    m = date.getMinutes() + ':';
    s = date.getSeconds();
    return Y+M+D+h+m+s;
}
// 基于准备好的dom，初始化echarts实例
//数据模型 time0 open1 close2 min3 max4 vol5 tag6 macd7 dif8 dea9
//['2015-10-19',18.56,18.25,18.19,18.56,55.00,0,-0.00,0.08,0.09] 
function deepcopy(obj) {

    var out = [], i = 0, len = obj.length;

    for (; i < len; i++) {

        if (obj[i] instanceof Array) {

            out[i] = deepcopy(obj[i]);

        }

        else out[i] = obj[i];

    }

    return out;

}
function splitData(rawData) {
    var categoryData = [];
    var values = [];
    var vols = [];
    var macds = [];
    var difs = [];
    var deas = [];
    for (var i = 0; i < rawData.length; i++) {
        categoryData.push(rawData[i].splice(0, 1)[0]);
        values.push(rawData[i]);
        vols.push(rawData[i][4]);
        macds.push(rawData[i][6]);
        difs.push(rawData[i][7]);
        deas.push(rawData[i][8]);
    }
    return {
        categoryData: categoryData,
        values: values,
        vols: vols,
        macds: macds,
        difs: difs,
        deas: deas
    };
}

function calculateMA(dayCount) {
    var result = [];
    for (var i = 0, len = data0.values.length; i < len; i++) {
        if (i < dayCount) {
            result.push('-');
            continue;
        }
        var sum = 0;
        for (var j = 0; j < dayCount; j++) {
            sum += data0.values[i - j][1];
        }
        result.push(sum / dayCount);
    }
    return result;
}
var oldArr = new Array();
let dataArr = [];
let tradeArr = [];
let asksArr = [];
let bidsArr = [];
let data0 = [];
let getTradeBuy = function(d){
    return tradeArr;
}
let getTradeSell = function(d){
    return tradeArr;
}
function keepTwoDecimalFull(num) {
    var result = parseFloat(num);
    if (isNaN(result)) {
    alert('传递参数错误，请检查！');
    return false;
    }
    result = Math.round(num * 100) / 100;
    var s_x = result.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0) {
    pos_decimal = s_x.length;
    s_x += '.';
    }
    while (s_x.length <= pos_decimal + 2) {
    s_x += '0';
    }
    return s_x;
   }
let tradeData = function (d) {
    let trade = d;
    if (tradeArr.length > 1000) {
        tradeArr.shift();
    }
    var t = trade.timestamp;
    t = new Date(t);
    currentIndex = 0;
    for (var k = 0; k < oldArr.length; k++) {
        var kt = new Date(oldArr[k][0]);
        if( kt.getTime() > t.getTime() ){
            break;
        }
        currentIndex = kt.getTime();
    } 
    var exist = false;
    if(currentIndex<=0){
        return;
    }
    for( var j =0;j<tradeArr.length;j++){
        if(tradeArr[j].side==trade.side && tradeArr[j].time == currentIndex){
            tradeArr[j].all += trade.qty*trade.price;
            exist = true;
            break;
        }
    }
    if (!exist){
        tradeArr.push({
            "side":trade.side,
            "time":currentIndex,
            "all":trade.qty*trade.price
        });
    }
}
let depthData = function (d) {
    console.log(d);
    let depth = d;
    if (asksArr.length > 1000) {
        asksArr.shift();
    }
    if (bidsArr.length > 1000) {
        bidsArr.shift();
    }
    var t = depth.timestamp;
    t = new Date(t);
    currentIndex = 0;
    for (var k = 0; k < oldArr.length; k++) {
        var kt = new Date(oldArr[k][0]);
        if( kt.getTime() > t.getTime() ){
            break;
        }
        currentIndex = kt.getTime();
    } 
   
    if(currentIndex<=0){
        return;
    }
    asksArr[currentIndex] = 0;
    bidsArr[currentIndex] = 0;
    //空单情况
    for( var j =0;j<depth.asks.length;j++){
        asksArr[currentIndex] += depth.asks[j][0]*depth.asks[j][1];
    }
    //买单情况
    for( var j =0;j<depth.bids.length;j++){
        bidsArr[currentIndex] += depth.bids[j][0]*depth.bids[j][1];
    }
    console.log(asksArr);
    console.log(bidsArr);
}
let klineData = function (d) {
    let tradeData = d;
    if (oldArr.length > 1000) {
        oldArr.shift();
    }
    var v = tradeData.candle;
    var t = v[0];
    t = new Date(t);
    v[0] = timestampToTime(t.getTime());
   
    for (var i = 1; i < v.length; i++) {
        v[i] = v[i] * 1;
    }

    let open = v[1];
    let close = v[4];
    let min = v[3];
    let max = v[2];
    v[2] = close;
    v[4] = max;
    v.push(t.getTime());
    v.push(0);
    v.push(0);
    var exist = false;
    for (var k = 0; k < oldArr.length; k++) {
        if (oldArr[k][0] == v[0]) {
            oldArr[k] = v;
            exist = true;
            break;
        }
    }
    if (!exist) {
        oldArr.push(v);
    }

    dataArr = deepcopy(oldArr);

    data0 = splitData(dataArr);
    option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            },
            formatter: function(params){
                console.log(params[0].data);
                var t = params[0].data[7];
                var all_buy = 0,all_sell = 0,buy_depth=0,sell_depth=0;
                console.log(tradeArr);
                for(var i=0;i<tradeArr.length;i++){
                    console.log(t);
                    if(t == tradeArr[i].time){
                        console.log(tradeArr[i]);
                        if(tradeArr[i].side=='buy'){
                            all_buy = tradeArr[i].all;
                        }
                        if(tradeArr[i].side=='sell'){
                            all_sell = tradeArr[i].all;
                        }
                    }
                }
                if(bidsArr[t]){
                    buy_depth = bidsArr[t];
                }
                
                if(asksArr[t]){
                    sell_depth = asksArr[t];
                }
                var res= '<div><span>开盘价：$ </span>'+params[0].data[1]+'</div>' +
                    '<div><span>收盘价 $：</span>'+params[0].data[2]+'</div>' +
                    '<div><span>最低价 $：</span>'+params[0].data[3]+'</div>'+
                    '<div><span>最高价 $：</span>'+params[0].data[4]+'</div>'+
                    '<div><span>买盘成交总量 $：</span>'+keepTwoDecimalFull(all_buy)+'</div>'+
                    '<div><span>卖盘成交总量 $：</span>'+keepTwoDecimalFull(all_sell)+'</div>'+
                    '<div><span>买盘深度 $：</span>'+keepTwoDecimalFull(buy_depth)+'</div>'+
                    '<div><span>卖盘深度 $：</span>'+keepTwoDecimalFull(sell_depth)+'</div>';
                return res
            }
        },
        grid: [{
            left: '3%',
            top: '1%',
            height: '58%'
        }, {
            left: '3%',
            right: '10%',
            top: '65%',
            height: '10%'
        }, {
            left: '3%',
            right: '10%',
            top: '78%',
            height: '10%'
        }],
        xAxis: [{
            type: 'category',
            data: data0.categoryData,
            scale: true,
            boundaryGap: false,
            axisLine: {
                onZero: false,
                lineStyle: {
                    color: 'red',
                }
            },
            splitLine: {
                show: false
            },
            splitNumber: 20
        }, {
            type: 'category',
            gridIndex: 1,
            data: data0.categoryData,
            axisLabel: {
                show: false
            },

        }, {
            type: 'category',
            gridIndex: 2,
            data: data0.categoryData,
            axisLabel: {
                show: false
            },

        }],
        yAxis: [{
            scale: true,
            splitArea: {
                show: true
            },
            axisLine: {
                lineStyle: {
                    color: 'red',
                }
            },
            position: 'right'
        }, {
            gridIndex: 1,
            splitNumber: 3,
            axisLine: {
                onZero: false,
                lineStyle: {
                    color: 'red'

                }
            },
            axisTick: {
                show: false
            },
            splitLine: {
                show: false
            },
            axisLabel: {
                show: true
            },
            position: 'right'
        }, {
            gridIndex: 2,
            splitNumber: 4,
            axisLine: {
                onZero: false,
                lineStyle: {
                    color: 'red'

                }
            },
            axisTick: {
                show: false
            },
            splitLine: {
                show: false
            },
            axisLabel: {
                show: true
            },
            position: 'right'
        }],
        dataZoom: [{
            type: 'inside',
            start: 100,
            end: 80
        }, {
            show: true,
            type: 'slider',
            y: '90%',
            xAxisIndex: [0, 1],
            start: 50,
            end: 100
        }, {
            show: false,
            xAxisIndex: [0, 2],
            type: 'slider',
            start: 20,
            end: 100
        }],
        series: [{
            name: '详情',
            type: 'candlestick',
            data: data0.values,
            markPoint: {
              data: [{
                name: 'XX标点'
              }]
            },
            markLine: {
              silent: true,
              data: [{
                yAxis: 2222,
              }]
            }
          },{
            name: 'Volumn',
            type: 'bar',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: data0.vols,
            itemStyle: {
                normal: {
                    color: function (params) {
                        var colorList;
                        if (data0.values[params.dataIndex][1] > data0.values[params.dataIndex][0]) {
                            colorList = '#ef232a';
                        } else {
                            colorList = '#14b143';
                        }
                        return colorList;
                    },
                }
            }
        }, {
            name: 'MACD',
            type: 'bar',
            xAxisIndex: 2,
            yAxisIndex: 2,
            data: data0.macds,
            itemStyle: {
                normal: {
                    color: function (params) {
                        var colorList;
                        if (params.data >= 0) {
                            colorList = '#ef232a';
                        } else {
                            colorList = '#14b143';
                        }
                        return colorList;
                    },
                }
            }
        }, {
            name: 'DIF',
            type: 'line',
            xAxisIndex: 2,
            yAxisIndex: 2,
            data: data0.difs
        }, {
            name: 'DEA',
            type: 'line',
            xAxisIndex: 2,
            yAxisIndex: 2,
            data: data0.deas
        }]
    };
    myChart.setOption(option);
};

function appendLog(msg) {
    console.log(msg);
}
let conn;
let testHelloWorld = function () {
    if (!conn) {
        alert("WebSockets Not Support.");
        return
    }
    conn.send("hello world!");
};
$(function () {
    let isConnect = false;
    let reconnectServer = function () {
        if (isConnect) {
            return;
        }
        isConnect = true;
        if (window["WebSocket"]) {
            let host = '127.0.0.1:8888';
            console.log("host:", host);
            conn = new WebSocket("ws://" + host);
            conn.onclose = function (evt) {
                appendLog("Connection Closed.", evt);
                setTimeout(reconnectServer, 2000);
                isConnect = false;
            };
            conn.onopen = function (evt) {
                appendLog("Connection Success.");
            };
            conn.onerror = function (evt) {
                appendLog("Connection Error.");
                setTimeout(reconnectServer, 2000);
                isConnect = false;
            };
            conn.onmessage = function (evt) {
                try {
                    let data = JSON.parse(evt.data);
                    if (data == undefined){
                        console.log(evt.data);
                        return
                    }
                    if(data.type=='kline'){
                        klineData(data.data);
                    }
                    if(data.type=='trade'){
                        tradeData(data.data);
                    }
                    if(data.type=='depth'){
                        depthData(data.data);
                    }
            }
            catch(err){
                console.log(err);
            }
            };
        } else {
            appendLog("WebSockets Not Support.")
        }
    };
    reconnectServer();
});